<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Controller;
use think\Request;
use think\facade\Cache;
use app\api\controller\Mqtt;
class Batteryba extends Api
{
    public function index()
    {
        if($this->request->isPost())
        {
            $list = ysh_select($this->request->controller());
            return fh(200,'success','',$list);
        }
    }
    //获取微信小程序后台AccessToken
    public function token()
    {
        if(!Cache::get('token') || (!Cache::get('time') || Cache::get('time') < time())){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
            $curl = curl_send(['url'=>$url]);
            $token = json_decode($curl['content'])->access_token;
            Cache::set('token',$token);
            Cache::set('time',time()+7200);
        }else{
            $token = Cache::get('token');
        }
        return $token;
    }
    //获取小程序码
    public function unlimited()
    {
        if($this->request->isPost())
        {
            $post = input('post.');
            $post = array_filter($post);
            if(!isset($post['id'])) return fh(200,'error','缺少机台编号',[]);
            if(!isset($post['class'])) return fh(200,'error','缺少金额id',[]);
            $jt = model('batteryba')->where('batterybaid','=',$post['id'])->find()->toArray();
            $token = $this->token();
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
            $data = "{\"scene\":\"pages/index/index?code=" . $post['class'] . "&id=".$jt['id'] ."\"}";
            $res = curl_send([
                'url'=>$url,
                'method'=>'post',
                'data'=>$data
            ]);
            //通过返回的参数保存在本地；
            file_put_contents('code/' . "wx" . $jt['id'] . '_' . $post['class'] . ".png", $res['content']);
            model('user')->save(['ewmimages'=>'/code/wx' . $jt['id'] . '_' . $post['class'] . ".png"],['id'=>$jt['id']]);
            return fh(200,'success','请求成功',['url'=>'https://baosheng.langqiyun.cn/code/wx' . $jt['id'] . '_' . $post['class'] . ".png"]);
        }
    }
    //机台的轮播图
    public function banner()
    {
    	$limit = input('limit') ?? 10;
    	$list = model('banner')->where('type','=',1)->paginate($limit);
    	if(!empty($list)){
    		$list = $list->toArray();
    		foreach ($list['data'] as $k=>$v)
	    	{
	    		if(!empty($v['img'])){
	    			$list['data'][$k]['img'] = 'https://baosheng.langqiyun.cn' . $v['img'];
	    		}
	    	}
    	}
    	return fh(200,'success','',$list);
    }
    //机台收到支付成功的通知后,告知服务器它以收到
    public function msg()
    {
    	if($this->request->isPost())
    	{
    		$post = post();
    		try{
    			//id:机台编号，orderid:订单号
    				$list = model('battery_order')->where([
    					['name','=',$post['id']],
    					['orderid','=',$post['orderid']]
    					])->find()->toArray();
    				model('battery_order')->save(['type'=>2],['id'=>$list['id']]);
    			}catch (\Exception $e){
            		return fh(200,'error','没有查询到该机台订单',[]);
        		}
        	return fh(200,'success','接受成功',[]);
    	}
    }
    //服务器定时轮循推送下发充电通知不成功的机台
    public function type()
    {
    	//支付1分钟了还没收到的机台;
    	$time = time()-60;
    	$list = model('battery_order')->where([
    		['type','=',1],
    		['status','=',2],
    		['create_time','<',$time]
    		])->with('batteryba')->select();
    	if(!empty($list)){
    		$list = $list->toArray();
	        $mqtt = new Mqtt($this->server, $this->port, $this->client_id); //实例化MQTT类
    		foreach ($list as $v){
    			if(empty($v['name']) || empty($v['batteryba'])){
    				continue;
    			}
    			// 发送给订阅号信息,创建socket,无sam队列
		        if ($mqtt->connect(true, NULL, $this->username, $this->password)) {
		            //如果创建链接成功
		            //参数1：主题，参数2：内容，参数3：我也不知道
		            $orderid = $v['orderid'];
		            $de_time = $v['batteryba']['de_time'];
		            $c_time = date('Y-m-d H:i:s',$v['create_time']);
		            $money = $v['money'];
		            $cdtime = $v['cd_time']*1*60;
		            $mqtt->publish("baosheng/pay/notift/" . $v['name'], "{
		            	'status':'success',
		            	'code':200,
		            	'message':'支付成功',
		            	'orderid':$orderid,
		            	'end_time':$de_time,
		            	'money':$money,
		            	'pay_time':$c_time,
		            	'utility_time'$cdtime:
		            	
		            }", 0);
		            //发送到 xxx3809293670ctr的主题 一个信息 内容为 setr=3xxxxxxxxx Qos 为 0
		            $mqtt->close();    //发送后关闭链接
		        }
    		}
    	}
    }
    //开机状态检查（机台注册）
    public function status()
    {
    	if($this->request->isPost())
    	{
    		$post = post();
    		if(!isset($post['id'])){
    			$id = uniqid();
    			$time = time();
    			//batterybaid:机台编号，type:当前机台是否在使用中（1是2否）,status:后台对机台的启动控制（1开2关）,de_time:充电结束时间
    			$data = ['batterybaid'=>$id,'type'=>2,'status'=>2,'create_time'=>$time,'update_time'=>$time,'de_time'=>'0000-00-00 00:00:00'];
    			try{
    				model('batteryba')->save($data);
    			}catch (\Exception $e){
            		return fh(200,'error','注册失败',[]);
        		}
        		//注册
        		$data['class'] = 1;
        		unset($data['create_time']);
        		unset($data['update_time']);
    		}else{
    			try{
    				$data = model('batteryba')->field('batterybaid,type,status,de_time')->where('batterybaid','=',$post['id'])->find()->toArray();
    			}catch (\Exception $e){
            		return fh(200,'error','查询失败',[]);
        		}
        		//状态检查
        		$data['class'] = 2;
    		}
    		return fh(200,'success','请求成功',$data);
    	}
    }
    //充电结束后回调
    public function last()
    {
    	if($this->request->isPost())
    	{
    		$post = post();
    		if(!isset($post['id'])) return fh(200,'error','缺少机台编号',[]);
			try{
	    		$jt = model('batteryba')->where('batterybaid','=',$post['id'])->find()->toArray();
	    		if($jt['type'] == 2 || $jt['status'] == 2) return fh(200,'error','当前设备没有在充电',[]);
	    		$order = model('battery_order')->where([
	    			['name','=',$post['id']],
	    			['status','=',2]
	    			])->find()->toArray();
	    		$a = model('batteryba')->save(['type'=>2],['id'=>$jt['id']]);
	    		$b = model('battery_order')->save(['status'=>3],['id'=>$order['id']]);
	    		if(!$a || !$b){
	    			return fh(200,'error','修改失败',[]);
	    		}
			}catch (\Exception $e){
        		return fh(200,'error','回调失败',[]);
    		}
        	return fh(200,'success','请求成功',[]);
    		
    	}
    }
}
